<template>
  <div class="house-management">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span>房屋管理</span>
          <el-button type="primary" size="small">刷新数据</el-button>
        </div>
      </template>
      
      <!-- 搜索和筛选区域 -->
      <div class="search-container">
        <div class="search-filters">
          <el-input
            v-model="searchParams.keyword"
            placeholder="搜索房屋信息"
            class="search-input"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <el-input
            v-model="searchParams.district"
            placeholder="区域"
            class="search-input"
            clearable
          ></el-input>

          <el-select v-model="searchParams.status" placeholder="房屋状态" clearable class="status-select">
            <el-option label="全部" value=""></el-option>
            <el-option label="出租中" value="出租中"></el-option>
            <el-option label="闲置" value="闲置"></el-option>
          </el-select>

          <el-select v-model="searchParams.decoration" placeholder="装修情况" clearable class="decoration-select">
            <el-option label="全部" value=""></el-option>
            <el-option label="精装" value="精装"></el-option>
            <el-option label="简装" value="简装"></el-option>
            <el-option label="毛坯" value="毛坯"></el-option>
          </el-select>

          <div class="price-range">
            <el-input-number 
              v-model="searchParams.min_rent" 
              :min="0" 
              placeholder="最低租金"
              class="price-input"
              controls-position="right"
            ></el-input-number>
            <span>-</span>
            <el-input-number 
              v-model="searchParams.max_rent" 
              :min="0" 
              placeholder="最高租金"
              class="price-input"
              controls-position="right"
            ></el-input-number>
          </div>

          <el-select v-model="searchParams.sort_by" placeholder="排序" clearable>
            <el-option label="默认排序" value=""></el-option>
            <el-option label="价格从低到高" value="price_asc"></el-option>
            <el-option label="价格从高到低" value="price_desc"></el-option>
            <el-option label="面积从小到大" value="area_asc"></el-option>
            <el-option label="面积从大到小" value="area_desc"></el-option>
          </el-select>
        </div>
        
        <div class="search-button-container">
          <el-button type="primary" @click="searchHouses">搜索</el-button>
        </div>
      </div>
      
      <!-- 房屋列表表格 -->
      <el-table
        :data="houseList"
        style="width: 100%"
        border
        stripe
        v-loading="loading"
      >
        <el-table-column prop="house_id" label="房屋ID" width="80" />
        <el-table-column prop="description" label="房屋描述" min-width="180" />
        <el-table-column prop="district" label="区域" width="100" />
        <el-table-column prop="address" label="详细地址" min-width="180" />
        <el-table-column prop="floor_area" label="面积(㎡)" width="100" />
        <el-table-column prop="house_type" label="户型" width="100" />
        <el-table-column prop="monthly_rent" label="价格(元/月)" width="120" />
        <el-table-column prop="decoration" label="装修" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '出租中' ? 'danger' : 'success'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewHouseDetails(scope.row.house_id)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'

const router = useRouter()
const loading = ref(false)
const searchParams = ref({
  keyword: '',
  district: '',
  house_type: '',
  status: '',
  decoration: '',
  min_rent: null,
  max_rent: null,
  sort_by: ''
})
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const houseList = ref([])

// 获取房屋列表
const fetchHouseList = async () => {
  loading.value = true
  try {
    console.log('Search params:', searchParams.value)
    
    const response = await axios.get('http://127.0.0.1:5000/api/houses/housesList', {
      params: {
        keyword: searchParams.value.keyword,
        district: searchParams.value.district,
        house_type: searchParams.value.house_type,
        status: searchParams.value.status,
        decoration: searchParams.value.decoration,
        min_rent: searchParams.value.min_rent,
        max_rent: searchParams.value.max_rent,
        sort_by: searchParams.value.sort_by ? searchParams.value.sort_by.split('_')[0] : '',
        order: searchParams.value.sort_by ? searchParams.value.sort_by.split('_')[1] : ''
      }
    })
    
    if (response.status === 200) {
      // 保存完整的房屋列表
      const allHouses = response.data
      total.value = allHouses.length
      
      // 计算当前页的数据
      const startIndex = (currentPage.value - 1) * pageSize.value
      const endIndex = startIndex + pageSize.value
      houseList.value = allHouses.slice(startIndex, endIndex)
    } else {
      ElMessage.error('获取房屋列表失败')
    }
  } catch (error) {
    console.error('获取房屋列表失败:', error)
    ElMessage.error('获取房屋列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 搜索房屋
const searchHouses = () => {
  currentPage.value = 1 // 搜索时重置为第一页
  fetchHouseList()
}

// 查看房屋详情
const viewHouseDetails = async (houseId) => {
  try {
    const response = await axios.get(`http://127.0.0.1:5000/api/houses/getHouseDetails/${houseId}`)
    if (response.status === 200) {
      router.push(`/house/${houseId}`)
    }
  } catch (error) {
    console.error('获取房屋详情失败:', error)
    ElMessage.error('获取房屋详情失败，请稍后重试')
  }
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchHouseList()
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 切换每页显示数量时，重置为第一页
  fetchHouseList()
}

onMounted(() => {
  fetchHouseList()
})
</script>

<style scoped>
.house-management {
  padding: 20px;
}

.main-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  display: flex;
  margin-bottom: 20px;
  gap: 8px;
  align-items: center;
}

/* 搜索区域左侧容器 */
.search-filters {
  display: flex;
  flex: 1;
  gap: 8px;
  align-items: center;
  min-width: 0;
}

/* 搜索按钮容器 */
.search-button-container {
  margin-left: auto;
  white-space: nowrap;
  padding-left: 8px;
}

.search-input {
  width: 180px;
  min-width: 180px;
}

.el-select {
  width: 100px !important;
  min-width: 100px;
}

/* 状态和装修情况选择器的特殊宽度 */
.status-select,
.decoration-select {
  width: 120px !important;
  min-width: 120px;
}

.price-range {
  display: flex;
  align-items: center;
  gap: 8px;
  white-space: nowrap;
}

.price-input {
  width: 160px !important;
  min-width: 160px;
}

/* 调整 el-input-number 的内部样式 */
.price-input :deep(.el-input__wrapper) {
  padding: 0 8px;
}

.price-input :deep(.el-input-number__decrease),
.price-input :deep(.el-input-number__increase) {
  min-width: 32px;
}

.price-input :deep(.el-input__inner) {
  padding: 0 8px;
  text-align: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>